#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QThread>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    qDebug() << "当前 MainWindow 线程对象的地址: " << QThread::currentThread();

    /*  sub Thread */
    m_sub_thread1 = new QThread;
    m_sub_thread2 = new QThread;

    task01 = new NetworkTask_01;
    task02 = new NetworkTask_02;

    task01->moveToThread(m_sub_thread1);
    task02->moveToThread(m_sub_thread2);

    m_sub_thread1->start();
    m_sub_thread2->start();

    connect(this, &MainWindow::sendDevAddr_XHY, task01, &NetworkTask_01::Task01);
    connect(this, &MainWindow::sendDevAddr_PPY, task02, &NetworkTask_02::Task02);

    //子线程与任务均析构
    connect(this, &MainWindow::destroyed,this, [=](){
        m_sub_thread1->quit();
        m_sub_thread1->wait();
        m_sub_thread1->deleteLater();

        m_sub_thread2->quit();
        m_sub_thread2->wait();
        m_sub_thread2->deleteLater();

        task01->deleteLater();
        task02->deleteLater();
    });

    connect(this, &MainWindow::send_disconnect_xxy, task01, &NetworkTask_01::recv_disconncet);
    connect(this, &MainWindow::send_disconnect_ppy, task02, &NetworkTask_02::recv_disconncet);
    connect(this, &MainWindow::send_query_xxy, task01, &NetworkTask_01::recv_query);
    connect(this, &MainWindow::send_query_ppy, task02, &NetworkTask_02::recv_query);

    connect( task01, &NetworkTask_01::task_recv_msg,this,&MainWindow::task01_recv_msg);
    connect( task02, &NetworkTask_02::task_recv_msg,this,&MainWindow::task02_recv_msg);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_btn_cnct_xhy_clicked()
{
    QString rmtIP = ui->let_ip_xhy->text();
    unsigned short rmtPort = ui->let_pt_xhy->text().toUShort();
    emit sendDevAddr_XHY(rmtIP, rmtPort);
}

void MainWindow::on_btn_cnct_ppy_clicked()
{
    QString rmtIP = ui->let_ip_ppy->text();
    unsigned short rmtPort = ui->let_pt_ppy->text().toUShort();
    emit sendDevAddr_PPY(rmtIP, rmtPort);
}

void MainWindow::on_btn_dsct_xhy_clicked()
{
    emit send_disconnect_xxy();
}

void MainWindow::on_btn_dsct_ppy_clicked()
{
    emit send_disconnect_ppy();
}

void MainWindow::on_btn_qruy_xhy_clicked()
{
    emit send_query_xxy();
}

void MainWindow::on_btn_qruy_ppy_clicked()
{
    emit send_query_ppy();
}

void MainWindow::task01_recv_msg(QByteArray recvMsg)
{
    ui->tbs_all->append(recvMsg);
    ui->tbs_xhy->append(recvMsg);
}

void MainWindow::task02_recv_msg(QByteArray recvMsg)
{
    ui->tbs_all->append(recvMsg);
    ui->tbs_ppy->append(recvMsg);
}
